<template>
    <div class='selectCity'>
        <h2 class="title">城市选择</h2>
        <!-- 
            属性:
                index-list	索引字符列表	string[] | number[]	A-Z

                index	索引字符	number | string	-

                <van-cell title="文本" />
                    title 内容展示
         -->
        <van-index-bar :index-list="indexList">
            <template v-for="(item,name) in citylist">
                <van-index-anchor :index="name" :key="name" />
                    <van-cell :title="ele.name" v-for="ele in item" :key="ele.id" @click="tiao"/>
            </template>            
        </van-index-bar>
    </div>
</template>

<script>
import api from '../../api/index'
export default {
    name: 'SearchCity',

    data() {
        return {
            citylist: {},
            city: ''
        };
    },

    async created() {
        const res = await api.getCity();
        console.log('res: ', res);
        if(res.data.errmsg === 'OK') {
            this.citylist = res.data.result.citylist;
        }else {
            console.log('SearchCity接口错误');
        }  
    },

    computed: {
        indexList() {
            return Object.keys(this.citylist);
        },
    },

    destroyed() {
        this.$bus.$emit('getCityName',this.city);
    },

    methods: {
        tiao(event) {
            // 本地存储
            //window.localStorage.setItem('city',event.target.innerText);
            // this.$router.go(-1);

            // 使用总线,传递数据时必须在组件的destroyed生命周期函数中执行
            this.city = event.target.innerText

            this.$router.push('/');
            document.documentElement.scrollTop = 0;
        }
    },
};
</script>

<style lang="less" scoped>
    .selectCity {
        background: #f5f5f5;
        .title {
            padding: 0.2rem;
        }
    }
</style>